package edu.cueb.wmis.controller;

import edu.cueb.wmis.pojo.Admin;
import edu.cueb.wmis.pojo.AdminLoginParam;
import edu.cueb.wmis.pojo.RespBean;
import edu.cueb.wmis.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * 登录
 */
@Api(tags = "LoginController")
@RestController
public class LoginController {

    @Autowired
    private IAdminService adminService;

//    @ApiOperation(value = "登录之后返回token")
//    @PostMapping("/login")
//    public RespBean login(AdminLoginParam adminLoginParam , HttpServletRequest request){
//        return adminService.login(adminLoginParam.getUsername() , adminLoginParam.getPassword() );
//    }
    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam,HttpServletRequest request){
        System.out.println("1111111");
        System.out.println(request);
        return adminService.login(adminLoginParam.getUsername() , adminLoginParam.getPassword() );
    }
    //获取当前用户信息
    @ApiOperation(value = "获取用户当前信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal){     //principal
        if(null == principal){
            return null;
        }
        String username = principal.getName();
        Admin admin = adminService.getAdminByUserName(username);
        admin.setPassword(null); //防范密码泄露的风险
        System.out.println(admin.getId());
        System.out.println(adminService.getRoles(admin.getId()));
        admin.setRoles(adminService.getRoles(admin.getId()));
        return admin;
    }
    //
    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout(){
        return RespBean.success("退出登录成功！");  //退出后前端需要将token的请求头删除，在登陆会被拦截器拦截。
    }
}